import { aesEncryteData, rsaEncrypt } from "./encryte";
import Base64 from "base-64";

let api = "";
if(process.env.NODE_ENV === "development"){
	if(process.env.VUE_APP_PLATFORM === "app-plus"){
		api = "https://yqjc.cezhiyun.com";
	}else{
		api = "/api"
	}
}else{
	api = "https://yqjc.cezhiyun.com";
}
const install = (Vue, vm) => {
	Vue.prototype.$u.http.setConfig({
		baseUrl: api,
		showLoading: false,
	});
	// 请求拦截部分，如配置，每次请求前都会执行，见上方说明
	Vue.prototype.$u.http.interceptor.request = (config) => {
		console.log("接口请求：",config.url+":",config.data);
		config.header.Authorization = "bearer " + uni.getStorageSync("token");
		let data = !config.data ? {} : config.data;
		let key = uni.getStorageSync("_key");
		let iv = uni.getStorageSync("_iv");

		let dataStr = JSON.stringify(data);
		let aesResult = aesEncryteData(dataStr,key,iv);
		
		let params = {
			key: rsaEncrypt(key),
			iv: rsaEncrypt(iv),
			data: Base64.encode(aesResult),
		};
		if(!config.url.includes("user_login") && !config.url.includes("web/article_detail") && !config.url.includes("web/article")){
			config.data = {data: params.data};
			config.header.key = params.key;
			config.header.iv = params.iv;
		}
		return config;
	}
	
	// 响应拦截，如配置，每次请求结束都会执行本方法
	Vue.prototype.$u.http.interceptor.response = (res) => {
		if(res.code == 200) {
			// res为服务端返回值，可能有code，result等字段
			// 这里对res.result进行返回，将会在this.$u.post(url).then(res => {})的then回调中的res的到
			// 如果配置了originalData为true，请留意这里的返回值
			return res;
		} else if(res.code == 0) {
			Vue.prototype.$clearStorage();
			// vm.$u.toast("登录已过期，请重新登录");
			const currentPage = getCurrentPages().pop().route;
			if(currentPage != "pages/login/login"){
				vm.$store.state.isLogin = false;
				uni.reLaunch({
					url: "/pages/login/login"
				});
			}
			return false;
		} else {
			uni.hideLoading();
			vm.$u.toast(res.message);
			// 如果返回false，则会调用Promise的reject回调，
			// 并将进入this.$u.post(url).then().catch(res=>{})的catch回调中，res为服务端的返回值
			// return false;
			return res;
		}
	}
}

export default {
	install
}